package vn.fpt.fsoft.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;

import vn.fpt.fsoft.dao.TrustDistrictDAO;
import vn.fpt.fsoft.entity.TrustDistrict;

/**
 * Servlet implementation class AmendTrustDistrict
 */
@WebServlet("/AmendTrustDistrict")
public class AmendTrustDistrict extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AmendTrustDistrict() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if("amend".equalsIgnoreCase(action)){
			Integer id = Integer.parseInt(request.getParameter("districtID"));
			String name= request.getParameter("name");
			String description=request.getParameter("description");
			boolean success=TrustDistrictDAO.amendTrustDistrict(id, name, description);
			if(success){
				out.write("Amending this trust district success!");
			}else {
				out.write("Amending this trust district fails! Already have this district name!");
			}
		}else if("getData".equalsIgnoreCase(action)){
			Integer districtID = Integer.parseInt(request.getParameter("districtID"));
			TrustDistrict td = TrustDistrictDAO.getDistrictById(districtID);
			JsonObject jsonObj = new JsonObject();
			jsonObj.addProperty("districtID", td.getTrustDistrictID());
			jsonObj.addProperty("districtName", td.getName());
			jsonObj.addProperty("description", td.getDescription());
			jsonObj.addProperty("regionName", td.getTrustRegion().getName());
			jsonObj.addProperty("active", td.getActive());
			out.write(String.valueOf(jsonObj));
		} else if ("markInActive".equals(action)) {
		    Integer id = Integer.parseInt(request.getParameter("districtID"));
		    TrustDistrict trustDistrict = TrustDistrictDAO.getDistrictById(id);
		    trustDistrict.setActive(false);
		    if (TrustDistrictDAO.amendTrustDistrict(trustDistrict)) {
		        out.write("Mark In-active seccess!!!");
		    } else {
		        out.write("Mark In-active fail!!!");
		    }
		} 
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
